package com.yzw.phonestoreservice.interceptor;

import com.yzw.phonecommen.common.R;
import com.yzw.phonecommen.constant.CheckResult;
import com.yzw.phonecommen.constant.SystemConstant;
import com.yzw.phonestoreservice.annotation.UnInterception;
import com.yzw.phonecommen.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @BelongsProject: springbootdome
 * @BelongsPackage: com.yu.sbmpsum1.interceptor
 * @Author: yanhongwei
 * @CreateTime: 2022-10-30  17:05
 * @Description: TODO 拦截器
 * @Version: 1.0
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod) {
            // 如果接口方法处理器  就会走这里
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            String methodName = method.getName();
            logger.info("====拦截到了方法：{}，在该方法执行之前执行====", methodName);
            //得到方法上的注解 根据注解判断 这个方法需不需要拦截
            // 使用UnInterception 注解标注的方法 直接放行
            UnInterception annotation = method.getAnnotation(UnInterception.class);
            if (null != annotation) {
                return true;
            }
            String token = request.getHeader("token");
            logger.info(token);
            if(StringUtils.isEmpty(token)){
                logger.info("token为空,请先登录");
                R r = R.error().code(SystemConstant.JWT_ERRCODE_NULL).message("token为空");
                // 向前端发送相应结果
                print(response,r);
                return false;
            } else{
                //token 验证
                CheckResult checkResult = JwtUtils.validateJWT(token);
                if(checkResult.isSuccess()){
                    return true;
                }else{
                    switch (checkResult.getErrCode()){
                        case SystemConstant.JWT_ERRCODE_FAIL:{
                            logger.info("token校验不通过");
                            R r = R.error().code(SystemConstant.JWT_ERRCODE_FAIL).message("token校验不通过");
                            // 向前端发送相应结果
                            print(response,r);
                            return false;
                        }

                        case SystemConstant.JWT_ERRCODE_EXPIRE:{
                            logger.info("token已过期");
                            R r = R.error().code(SystemConstant.JWT_ERRCODE_EXPIRE).message("token已过期");
                            // 向前端发送相应结果
                            print(response,r);
                            return false;
                        }

                    }
                }
            }

        }
//        logger.info("执行方法之前执行(Controller方法调用之前)");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        logger.info("执行完方法之后进执行(Controller方法调用之后)，但是此时还没进行视图渲染");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        logger.info("整个请求都处理完咯，DispatcherServlet也渲染了对应的视图咯，此时我可以做一些清理的工作了");
    }

    public void print(HttpServletResponse response,R r){

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.println(r);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


